#!/usr/bin/env python
# encoding: utf-8
"""
news_column.py

Created by Manabu Terada on 2009-09-26.
Copyright (c) 2009 CMScom. All rights reserved.
"""
from zope import schema
from Acquisition import aq_inner
from zope.component import getMultiAdapter
from zope.formlib import form
from zope.interface import implements
from Products.CMFPlone.utils import getSiteEncoding
from plone.app.portlets.portlets import base
from plone.memoize import ram
from plone.portlets.interfaces import IPortletDataProvider
from plone.memoize.compress import xhtml_compress
from plone.memoize.instance import memoize
from plone.app.portlets.cache import render_cachekey
from Products.CMFCore.utils import getToolByName
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from c2.site.icos09 import icos09MessageFactory as _
from plone.memoize.instance import memoize

from c2.site.icos09.config import PORTLET_CHAR_LIMIT

class INewsColumnPortlet(IPortletDataProvider):
    """"""
    count = schema.Int(title=_(u'Number of items to display'),
                       description=_(u'How many items to list.'),
                       required=True,
                       default=5)
    state = schema.Tuple(title=_(u"Workflow state"),
                        description=_(u"Items in which workflow state to show."),
                        default=('published', ),
                        required=True,
                        value_type=schema.Choice(
                            vocabulary="plone.app.vocabularies.WorkflowStates")
                        )

class Assignment(base.Assignment):
    implements(INewsColumnPortlet)
    def __init__(self, count=5, state=('published', )):
        self.count = count
        self.state = state

    @property
    def title(self):
        return _(u"News Column Portlet")

class Renderer(base.Renderer):
    _template = ViewPageTemplateFile('news_column.pt')

    @ram.cache(render_cachekey)
    def render(self):
        return xhtml_compress(self._template())

    def navigation_root_url(self):
        portal_state = getMultiAdapter((self.context, self.request),
                                            name=u'plone_portal_state')
        return portal_state.navigation_root_url()
    
    @property
    def available(self):
        return True
        # return len(self._data('/news/TFCAnews')) + len(self._data('/news/WalfareNews'))

    def get_items(self, path):
        return self._data(path)
    
    def get_column_types(self):
        types = [('/news/TFCAnews', u'TFCA消息'), 
                ('/news/WalfareNews', u'社福補助News'),
                 ]
        return types

    def sefe_title(self, title):
        s = title
        if not isinstance(s, unicode):
            s = s.decode(getSiteEncoding(self), 'replace')
        if len(s) > PORTLET_CHAR_LIMIT:
            s = s[:PORTLET_CHAR_LIMIT] + '...'
        return s

    @memoize
    def _data(self, path):
        context = aq_inner(self.context)
        catalog = getToolByName(context, 'portal_catalog')
        portal_state = getMultiAdapter((self.context, self.request), 
                                        name=u'plone_portal_state')
        portal = portal_state.portal()
        column_path = path
        if not column_path.startswith('/'):
            column_path = '/' + column_path
        path = '/'.join(portal.getPhysicalPath()) + column_path
        limit = self.data.count
        state = self.data.state
        return catalog(portal_type='News Item',
                       review_state=state,
                       path=path,
                       sort_on='Date',
                       sort_order='reversed',
                       sort_limit=limit)[:limit]

class AddForm(base.AddForm):
    form_fields = form.Fields(INewsColumnPortlet)

    def create(self, data):
        return Assignment(**data)

class EditForm(base.EditForm):
    form_fields = form.Fields(INewsColumnPortlet)

